<?php
// 应用公共文件

//获取配置信息
function get_app_config($key = "")
{
    $appConfig = cache("appConfig");
    if (!empty($key)) {
        //获取指定的配置项
        if ($appConfig[$key]) {
            return [$key => $appConfig[$key]];
        }
        $data         = db('config')->where('key', $key)->find();
        $config[$key] = unserialize($data['value']);
        return $config;
    } else {
        //获取全部的配置信息
        if ($appConfig) {
            return $appConfig;
        }
        $configs = db('config')->select();
        $config  = [];
        foreach ($configs as $c) {
            $config[$c['key']] = unserialize($c['value']);
        }
        cache('appConfig', $config, 3600); //缓存
        return $config;
    }
}

//获取单项配置
function config($key = 'site')
{
    return get_app_config($key)[$key];
}

//获取网站基本信息
function site($name)
{
    $site = get_app_config('site');
    return $site['site'][$name] ? $site['site'][$name] : '';
}

//写网站日志到数据库
function add_admin_log($content)
{
    $log                = array();
    $log['content']     = $content;
    $log['create_time'] = time();
    $log['create_ip']   = request()->ip();
    if (!db('admin_log')->insert($log)) {
        return false;
    }
    return true;
}

//增加货币
function inc_money($uid, $username, $currency = 'money', $money = 1, $message = '', $type = 1)
{
    if(db('user')->where('id',$uid)->setInc($currency,$money)){
        db('user')->where('id',$uid)->setInc('total_money',$money); //累计总收入
        if($type == 2){
            db('user')->where('id',$uid)->setInc('invite_money',$money); //累计邀请收入
        }
        $record = [
            'user_id' => $uid,
            'username' => $username,
            'currency' => $currency,
            'money' => $money,
            'message' => $message,
            'type' => $type,
            'time' => time()
        ];
        if(db('money_record')->insert($record)){
            return true;
        }
    }
    return false;
}

//减少货币
function dec_money($uid, $username, $currency = 'money', $money = 1, $message = '', $type = 1)
{
    if(db('user')->where('id',$uid)->setDec($currency,$money)){
        $record = [
            'user_id' => $uid,
            'username' => $username,
            'currency' => $currency,
            'money' => -$money,
            'message' => $message,
            'type' => $type,
            'time' => time()
        ];
        if(db('money_record')->insert($record)){
            return true;
        }
    }
    return false;
}

//获取文件修改时间
function get_file_time($file, $DataDir)
{
    $a    = filemtime($DataDir . $file);
    $time = date("Y-m-d H:i:s", $a);
    return $time;
}

//获取文件的大小
function get_file_size($file, $DataDir)
{
    $perms = stat($DataDir . $file);
    $size  = $perms['size'];
    $kb    = 1024;
    $mb    = 1024 * $kb;
    $gb    = 1024 * $mb;
    $tb    = 1024 * $gb;
    if ($size < $kb) {
        return $size . " B";
    } else if ($size < $mb) {
        return round($size / $kb, 2) . " KB";
    } else if ($size < $gb) {
        return round($size / $mb, 2) . " MB";
    } else if ($size < $tb) {
        return round($size / $gb, 2) . " GB";
    } else {
        return round($size / $tb, 2) . " TB";
    }
}

//删除指定目录以及文件
function delete_dir($dir)
{
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                delete_dir($fullpath);
            }
        }
    }
    closedir($dh);
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 系统邮件发送函数
 * $to ='email@qq.com';
 * $name ='123456';
 * $subject ='QQ邮件发送测试';
 * $content ='恭喜你，邮件测试成功。';
 * send_mail($to,$name,$subject,$content);
 */
function send_mail($to, $name, $subject = '', $body = '', $attachment = null)
{
    $config        = get_app_config('email');
    $config        = $config['email'];
    $mail          = new \PHPMailer();
    $mail->CharSet = 'UTF-8';
    $mail->IsSMTP();
    $mail->SMTPDebug  = isset($config['debug']) ? $config['debug'] : 0; // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth   = true;
    $mail->SMTPSecure = 'ssl';
    $mail->Host       = $config['host'];
    $mail->Port       = $config['port'];
    $mail->Username   = $config['user']; // SMTP服务器用户名
    $mail->Password   = $config['pass']; // SMTP服务器密码
    $mail->SetFrom($config['user'], $config['from']);
    $replyEmail = ''; //留空则为发件人EMAIL
    $replyName  = ''; //回复名称（留空则为发件人名称）
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if (is_array($attachment)) {
        // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

/**
 * 获取等级信息
 */
function get_level_name($level)
{
    $name = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
    return $name[$level - 1] . '级创客';
}

/**
 * 获取明细记录类型
 */
function get_currency_type($type)
{
    $types = [
        '1' => '激活账户',
        '2' => '直推奖励',
        '3' => '复投账户',
        '4' => '每日分红',
        '5' => '代理充值',
        '6' => '用户充值',
        '7' => '申请提现',
        '8' => '即时转账',
        '9' => '后台操作',
        '10'=> '挂售订单',
        '11'=> '撤销挂单',
        '12'=> '接单返利',
        '13'=> '取消接单',
        '14'=> '撤单补偿',
        '15'=> '超时惩罚',
        '16'=> '超时补偿',
        '17'=> '收分红奖',
        '18'=> '收推荐奖',
        '19'=> '成为代理'
    ];
    return $types[$type];
}

/**
 * 通过uid获取用户信息
 * $field = false 返回所有字段
 */
function get_userinfo($user_id, $field = 'username')
{
    $user = db('user')->find($user_id);
    if ($field) {
        return $user[$field];
    }
    return $user;
}

/**
 * 发送系统消息
 */
function send_message($user_id, $info, $send_id = 0){
    $result = db('user_msg')->insert([
        'send_user_id' => $send_id,
        'receive_user_id' => $user_id,
        'info' => $info,
        'act_ip' => request()->ip(),
        'add_time' => time()
    ]);
    return $result;
}